<template>
  <el-menu
    class="v-menu"
    router
    :default-active="activePath"
    :collapse="collapse"
    :collapse-transition="false"
  >
    <pure-comp :data="menus" />
  </el-menu>
</template>

<script>
export default {
  props: {
    collapse: Boolean,
    menus: {
      type: Array,
      default () {
        return []
      }
    },
    activePath: String
  },
  components: {
    PureComp: {
      functional: true,
      props: {
        data: {
          type: Array,
          default () {
            return []
          }
        }
      },
      methods: {},
      render (h, ctx) {
        const { data: menus } = ctx.props
        function getRoutePath (path, prefix) {
          return (prefix + '/' + path).replace(/\/+/g, '/')
        }
        const renderItem = (menus, prefixPath) => {
          return menus
            .filter(menu => !menu.meta || !menu.meta.hideInMenu)
            .map(menu => {
              let { meta = {}, children } = menu
              if (children) {
                children = children.filter(
                  it => !it.meta || !it.meta.hideInMenu
                )
              }
              if (children) {
                return children.length > 1 ? (
                  <el-submenu index={getRoutePath(menu.path, prefixPath)}>
                    <template slot="title">
                      <i class={meta.icon || 'el-icon-menu'}></i>
                      <span>{menu.meta && menu.meta.title}</span>
                    </template>
                    {renderItem(children, prefixPath + menu.path)}
                  </el-submenu>
                ) : children.length === 1 ? (
                  <el-menu-item
                    index={getRoutePath(
                      children[0].path,
                      prefixPath + menu.path
                    )}
                  >
                    <i
                      class={
                        (children[0].meta && children[0].meta.icon) ||
                        'el-icon-menu'
                      }
                    ></i>
                    <span slot="title">
                      {children[0].meta && children[0].meta.title}
                    </span>
                  </el-menu-item>
                ) : null
              } else {
                const { meta = {} } = menu
                return (
                  <el-menu-item index={getRoutePath(menu.path, prefixPath)}>
                    <span slot="title">
                      <span class="slug">{meta.slug} </span>
                      <span>{meta.title}</span>
                    </span>
                  </el-menu-item>
                )
              }
            })
        }
        return renderItem(menus, '')
      }
    }
  },
  computed: {}
}
</script>
